<template>
  <div>
    <!--数据过滤-->
    <div class="filter-panel">
      <ul>
        <li
          v-for="item in filterList"
          :key="item.id"
          :class="{ active: item.active }"
          @click="checkItem(item)"
        >
          <span>{{ item.label }}</span>
          <span>({{ item.count }})</span>
        </li>
      </ul>
    </div>
    <div id="SceneView">
      <div id="mapView"></div>
    </div>
  </div>
</template>

<script>
import typePoints from "../assets/mockData/pointType";
import InitArcGisJs from "../utils/loadGisModules";
export default {
  name: "trackMobile",
  data() {
    return {
      ARCGIS: {}, //arcgis模块集合
      filterList: [
        { id: 0, count: 0, label: "星级点", value: "XINGXING", active: true },
        { id: 1, count: 0, label: "信号塔", value: "SIGNALBOX", active: true },
        { id: 2, count: 0, label: "商店", value: "SHOPPING", active: true }
      ],
      view: {}
    };
  },
  async created() {
    console.log(typePoints);
    this.ARCGIS = await InitArcGisJs.init();
    let { Map, TileLayer, SceneView } = this.ARCGIS;
    const map = new Map({
      // basemap: "streets-night-vector",
      // showLabels: true,
      // maxZoom: 15,
      // zoom: 7,
      // minZoom: 6,
      // logo: false,
      // height: "100%",
      // fadeOnZoom: true
    });
    this.map = map;
    const CAMERA_Z = 27000,
      CAMERA_CENTER = [121.45897884146042, 31.246522700030482],
      // VIEW_ZOOM = 6.363478077483849;
      VIEW_ZOOM = 13;
    // VIEW_ZOOM_SPACE = 0.3;
    // 创建地图实例map
    this.view = new SceneView({
      container: "mapView",
      map: this.map,
      qualityProfile: "high"
      // camera: {
      //   position: {
      //     x: CAMERA_CENTER[0],
      //     y: CAMERA_CENTER[1],
      //     z: CAMERA_Z
      //     // spatialReference: { wkid: 102100 }
      //   },
      //   tilt: 0
      // },
      // zoom: VIEW_ZOOM,
      // center: CAMERA_CENTER,
      // qualityProfile: "medium", //  high, medium, low
      // viewingMode: "local",
      // screenSizePerspectiveEnabled: true,
      // highlightOptions: {
      //   haloOpacity: 0
      // }
    });
    var tiledUrl =
      "https://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineCommunity/MapServer";
    var tiledLayer = new TileLayer({ url: tiledUrl });
    this.map.add(tiledLayer);
    let list = [];
    this.view.on("click", event => {
      var screenPoint = {
        //当前点击的经纬度
        x: event.x,
        y: event.y
      };
      let { longitude: x, latitude: y } = event.mapPoint;
      list.push([x, y]);
      console.log(JSON.stringify(list));
      this.view.hitTest(screenPoint).then(function(response) {
        let { latitude, longitude } = response.ground.mapPoint;
        console.log(response);
        if (response.results.length > 0 && response.results[0].graphic) {
          console.log("这是当前点击的点位信息", response.results);
        }
      });
    });
    this.view.when(
      () => {
        // 地图加载完成
        setTimeout(() => {
          this.view.goTo({
            // 视角切换动画
            center: [121.45897884146042, 31.246522700030482], //终点坐标
            heading: 360, // 面向正南
            z: 10000,
            tilt: 0, //视图角度cos
            zoom: 13 //放大等级
          });
          this.showTypePotins();
        }, 1000);
        // 撒点动态图
      },
      function(error) {
        console.error(error);
        alert("加载失败,稍后重新加载");
        window.reload();
      }
    );
  },
  mounted() {},
  methods: {
    showTypePotins() {
      const graphics = [];
      let { Graphic } = this.ARCGIS;
      // 循环数组 将每个点位创建成一个图形（Graphic）
      typePoints.forEach(item => {
        const [x, y] = item.location;
        let graphic = new Graphic({
          //每个点的地理属性
          geometry: {
            type: "point",
            x,
            y,
            spatialReference: {
              wkid: 4326 //统一坐标系
            }
          },
          //每个点位的属性 （对应下方的FeatureLayer.fields）
          attributes: { ...item }
        });
        graphics.push(graphic);
      });
      // 初始化图层设备
      this.initDeviceLayer(graphics);
    },
    // 初始化图层设备
    initDeviceLayer(source) {
      let { FeatureLayer } = this.ARCGIS;
      // 计算数量
      this.countDeviceData(typePoints);
      var arr = this.filterList;
      var uniqueValueInfos = arr.map((item, index) => {
        return {
          value: item.value,
          symbol: {
            type: "picture-marker",
            url: require(`@/assets/images/svg/camera_m_${index + 1}.svg`)
          }
        };
      });
      const layer = new FeatureLayer({
        id: "deviceLayer",
        title: "设备图层",
        //从attributes中获取的内部fields
        fields: [
          {
            name: "ObjectID",
            type: "oid"
          },
          {
            name: "id",
            type: "string"
          },
          {
            name: "typeValue",
            type: "string"
          },
          {
            name: "name",
            type: "string"
          },
          {
            name: "desc",
            type: "string"
          }
        ],
        //让所有fields对外可访问
        outFields: ["*"],
        objectIdField: "ObjectID",
        geometryType: "point",
        source: [], //先把图层添加到地图上之后 再对图层进行添加点位的操作 故而这里先为空值
        renderer: {
          type: "unique-value",
          //提取typeValue作为渲染图标类型的标识
          valueExpression: `return $feature.typeValue`,
          //所有图标类型声明
          uniqueValueInfos,
          //根据缩放程度调整尺寸
          visualVariables: [
            {
              type: "size",
              valueExpression: "$view.scale",
              stops: [
                { value: 500000, size: 10 },
                { value: 250000, size: 20 },
                { value: 125000, size: 30 },
                { value: 32000, size: 30 }
              ]
            }
          ]
        },
        popupTemplate: {
          title: "{name}",
          content: [
            {
              type: "fields",
              fieldInfos: [
                {
                  label: "名称",
                  fieldName: "name"
                },
                {
                  label: "id",
                  fieldName: "id"
                },
                {
                  label: "类型",
                  fieldName: "typeValue"
                },
                {
                  label: "描述",
                  fieldName: "desc"
                }
              ]
            }
          ]
        }
      });
      this.map.add(layer);
      // resolve返回添加的source
      layer.applyEdits({ addFeatures: source }).then(results => {
        console.log(`deleteFeatures:${results.deleteFeatureResults.length}`);
        console.log(`addFeatures:${results.addFeatureResults.length}`);
      });
    },
    checkItem(item) {
      // 改变css样式
      item.active = !item.active;
      // 取出 当前选中的类型的values 状态（typeValue）
      const values = this.filterList
        .filter(item => item.active == true)
        .map(item => item.value);
      this.filterDeviceLayer({ mode: "typeValue", values });
    },

    /**
     * 前端过滤图层数据
     * mode {String} 过滤属性名
     * values {Array} 过滤值数组
     */
    filterDeviceLayer({ mode, values = [] } = {}) {
      const deviceLayer = this.map.findLayerById("deviceLayer");
      this.view.whenLayerView(deviceLayer).then(function(layerView) {
        let queryStr = "";
        if (values.length > 0) {
          queryStr += values
            .map(statusVal => {
              return `${mode}='${statusVal}'`;
            })
            .join(" OR ");
        }
        // sql语句 查询 typeValue='SIGNALBOX' OR typeValue='SHOPPING'
        // 前提条件是查询的字段需要存在于fields里 也就是存在于attributes对象里
        layerView.filter = { where: queryStr };
        //重新渲染
        deviceLayer.refresh();
      });
    },

    //计算各状态的设备数量
    countDeviceData(data) {
      const KEYMAP = {
        XINGXING: { count: 0, index: 0 },
        SIGNALBOX: { count: 0, index: 1 },
        SHOPPING: { count: 0, index: 2 }
      };
      data.forEach(item => {
        var match = KEYMAP[item.typeValue];
        if (match) {
          match.count++;
        }
      });
      Object.keys(KEYMAP).forEach(key => {
        const { index, count } = KEYMAP[key];
        this.filterList[index].count = count;
      });
      // console.log(this.filterList)
    }
  }
};
</script>

<style>
@import "https://js.arcgis.com/4.20/esri/css/main.css";
html,
body,
#mapView {
  padding: 0;
  margin: 0;
  height: 100%;
  width: 100%;
}
.dot_box {
  z-index: 2;
  position: fixed;
  width: 20px;
  height: 20px;
  background: #0080ff;
  border-radius: 50%;
}
.line_ele {
  z-index: 2;
  position: absolute;
  top: 50%;
  left: 0;
  margin-top: -1px;
  height: 1px;
  border-bottom: 1px solid #0080ff;
}
.box {
  z-index: 2;
  display: none;
  position: fixed;
  width: 300px;
  height: 300px;
  border: 2px solid #ddd;
}
#SceneView {
  position: absolute;
  width: 100%;
  height: 100%;
}
.esri-component.esri-attribution.esri-widget {
  display: none;
}
.filter-panel {
  position: fixed;
  top: 0;
  right: 10px;
  z-index: 9;
}
li {
  padding: 0 2em;
  background: transparent url("~@/assets/images/svg/check.svg") no-repeat 8px
    center;
  cursor: pointer;
  text-align: left;
  list-style: none;
}
.active {
  background: transparent url("~@/assets/images/svg/checked.svg") no-repeat 8px
    center;
}
li:hover {
  background-color: #0088ee;
  color: #fff;
}
</style>
